#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################
# Author: 廖勇彬(LIAO.YONGBIN)
# Created Time: 2025-01-04 18:18:51
################################################
# ===============================================
import os
from ftplib import FTP
import re
from datetime import datetime, date, timedelta


# 链接ftp
def ftpconnect(host, username, password):
    try:
        ftp = FTP()
        ftp.encoding = 'gbk'
        ftp.set_pasv(True)
        ftp.set_debuglevel(0)
        ftp.connect(host, 21)
        ftp.login(username, password)
        return ftp
    except Exception as error:
        print("FTP连接或登录失败，错误描述为:%s" % error)
        pass


# 遍历输出文件和 size
def getfile(ftp, path):
    ftp.cwd(path)
    filelist = []
    # 读取目录下的文件列表
    # ftp.retrlines('LIST', filelist.append)
    ftp.retrbinary('LIST', filelist.append)
    filelist = str(filelist[0], encoding="utf-8").split("\n")
    for f in filelist:
        if len(f) > 0:
            fileName = re.split(r'\s+', f)[-2]
# 判断是否为目录
            if f.startswith('d'):
                # 此处的 49 为打印出的各文件列表信息截取，根据实际情况更改
                path_a = ftp.pwd() + fileName + '/'
                getfile(ftp, path_a)
                ftp.cwd('..')
            else:
# 打印空的 csv 文件
                if os.path.splitext(fileName)[1] == '.csv' and ftp.size(ftp.pwd() + fileName) == 0:
                    print("file: " + ftp.pwd() + fileName + " size: " + str(ftp.size(ftp.pwd() + fileName)))


# 检查是否存在头一天日期的文件夹
def checkFolder(ftp, path, folderName):
    ftp.cwd(path)
    filelist = []
# 读取目录下的文件列表
# ftp.retrlines('LIST', filelist.append)
    ftp.retrbinary('LIST', filelist.append)
    filelist = str(filelist[0], encoding="utf-8").split("\n")

    for f in filelist:
        fList = re.split(r'\s+', f)
# print(fList[-1] +" "+ folderName)
# 判断是否为目录
        if f.startswith('d') and fList[-2] == folderName:
            return True
    return False


# 执行主函数
def main():


    ftp = ftpconnect("xx.xx.xx.xx", "xx", "xx")
# 获取头一天日期
yesterday = (date.today() + timedelta(days=-1)).strftime("%Y%m%d")
if checkFolder(ftp, ftp.pwd(), yesterday):
    getfile(ftp, ftp.pwd() + yesterday)
    pass
else:
    print("不存在昨天的文件夹")
    ftp.quit()
# 控制台执行时触发主函数
if __name__ == '__main__':
    main()
